package com.CMUBiS.PageServlets;
import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import com.CMUBiS.Data.Error;
import com.CMUBiS.Data.Footer;
import com.CMUBiS.Data.GlobalVars;
import com.CMUBiS.Data.Header;
import com.CMUBiS.PageControllers.*;
import com.CMUBiS.util.StopWatch;
import com.CMUBiS.util.User;

/**
 * This servlet is a blank example
 * 
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 * @version 0.1
 * @since 0.1
 * @date 04/05/2011
 * 
 */
@WebServlet(name="LoginServlet", urlPatterns="/login")
public class LoginServlet extends HttpServlet {
	
	
	
	private static final long serialVersionUID = 6475041006628458743L;
	private static final String EMPTY = "";
	private static final String title = "Login";
	
	/**
	 * Get the page, calls the page to be made
	 * We used to check the parameters in here, but I moved it to a controller object to keep the logic away from the layout
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(GlobalVars.isHTML4){
			makePage(request, response, Boolean.FALSE);
		}else{
			
			//response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			//System.out.println(request.getParameter("username")+" : "+ request.getParameter("password"));
			int userID = GlobalVars.db.checkUsernamePassword(request.getParameter("username"), request.getParameter("password"));
			String authToken ="";
			if(userID>0){
				authToken = GlobalVars.db.makeNewAuthToken(userID);
			}
			out.println("{\"userID\":\""+userID+"\",\"authToken\":\""+authToken+"\"}");
			//System.out.println("{\"userID\":\""+userID+"\",\"authToken\":\""+authToken+"\"}");
			out.close();
		}
	}
	
	/**
	 * Get the page, we can just pass this to doPost since the client generator will be posting userIDs and authTokens all the time
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(GlobalVars.isHTML4){
			makePage(request, response, Boolean.TRUE);
		}else{
			
			//response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			int userID = GlobalVars.db.checkUsernamePassword(request.getParameter("username"), request.getParameter("password"));
			String authToken ="";
			User curUser = null;
			//if(userID>0){
				authToken = GlobalVars.db.makeNewAuthToken(userID);
				curUser = GlobalVars.db.getUser(userID);
			//}
			out.print("{\"userID\":\""+userID+"\",\"authToken\":\""+
					authToken+"\",\"email\":\""+
					curUser.getEmail()+"\",\"firstName\":\""+
					curUser.getFirstName()+"\",\"lastName\":\""+
					curUser.getLastName()+"\"}");
			out.close();
			
			System.out.println(request.getParameter("username")+" : "+ request.getParameter("password"));
			System.out.println("{\"userID\":\""+userID+"\",\"authToken\":\""+authToken+"\"}");
		}
	}
	
	/**
	 * This method starts the page timer, writes the header, creates the HTML for the page, writes the stats, and the footer
	 * 
	 * @param request The incoming user request
	 * @param response  The out going user response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void makePage(HttpServletRequest request, HttpServletResponse response, Boolean isGet)  throws ServletException, IOException {
		if(request !=null && response != null){
			
			// Do the timer if we are collecting stats
			StopWatch timer;
			if(GlobalVars.collectStats){
				timer = new StopWatch();
				timer.start();
			}
			
			// Create a new page controller for this page, it will get and process the data
			LoginController vars = new LoginController();
			vars.checkInputs(request);
			
			// If the username and password are present then check them
			if(vars.getErrors().size() == 0){
				if(vars.login()){
					timer.stop();
					response.sendRedirect(vars.getRedirectURL());
				}
			}
			
			// We are using PrintWriter to be friendly to the international community. PrintWrite auto-converts coding
			PrintWriter out = response.getWriter();
	
			// Set the return type
			
			
			
			// If the output is to be suppressed then we'll redirect the output
			if(vars.getSuppressOutput())
				out = new PrintWriter(GlobalVars.blackHole);
			
			// Do HTML4 or 5 depending on the global variables
			if(GlobalVars.isHTML4){
				response.setContentType("text/html");
				// Write the page header
				Header.writeHeader(out, title, vars.getUserIDString(), vars.getAuthTokenString());
				createHTML4(out, vars, isGet);
				// Redirect the output to start writing the the user again in case we were putting it in the black hole
				out = response.getWriter();
				
				//
				// Output any errors. These don't need to be too pretty since we hope there isn't any!
				// We put them here to help with debug and info, the page above should show pretty ones for users
				 
				if(GlobalVars.printAllErrors){
					out.println("<BR />Errors: " + vars.getErrors().size());
					for(Error error: vars.getErrors())
						out.println("<BR />" + error.getErrorNumber() + " " +error.toString());
				}
				
				
				//  Process the page time
				 
				if(GlobalVars.collectStats){
					timer.stop();
					vars.setTotalTime(timer.getTimeTaken());
					GlobalVars.addStats(request, out, vars);
				}
				
				// Write the page footer
				Footer.writeFooter(out);
			}else{}
		}
	}
	
	/**
	 * Creates the HTML4 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML4(PrintWriter out, LoginController vars, Boolean isGet){
		if(out != null && vars != null)
		try{
			// Get the data needed to display the page
			vars.getHTML4Data();
			vars.processHTML4();
			
			// Make the login form
			out.println("<form name=\"login\" action=\"login\" method=\"POST\">");
			out.println("<div id=\"center\">");	
			
			// Make the username box
			out.println("<div id=\"floatright\">Username: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"username\" size=\"30\" value=\"" + vars.getUsername() + "\"/> </div>");
			
			// Make the password box
			out.println("<div id=\"floatright\">Password: </div>");
			out.println("<div id=\"floatcenter\"> <input type=\"text\" name=\"password\" size=\"30\" value=\""+ vars.getPassword() + "\"/> </div>");
			
			out.println("<div id=\"floatright\"><input type=\"submit\" value=\"Login\"></div>");
			
			out.println("</div>");
			out.println("</form>");
			
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Creates the HTML5 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML5(PrintWriter out, LoginController vars, Boolean isGet){
		if(out != null && vars != null)
		try{
			// Get the data needed to display the page
			vars.getHTML5Data();
			vars.processHTML5();
			
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
